(function (window, $) {
    var menu = window.menu = function () {
    }
    $(function () {
        initTree();
        $('#form-menu').bootstrapValidator({
            feedbackIcons: {
                valid: 'fa fa-check',
                invalid: 'fa fa-remove',
                validating: 'fa fa-refresh'
            }
        }).on('success.form.bv', function (e) {
            e.preventDefault();
            var $form = $(e.target);
            $.ajax({
                url: $form.attr('action'),
                type: 'post',
                dataType: 'json',
                data: $form.serialize(),
                success: function (rs) {
                    base.ajaxBack(rs, function () {
                        $form.find('[name=id]').val(rs.data.id);
                        $('#menu-remove').prop('disabled', false);
                        initTree();
                    });
                }
            });
        });
        $('#menu-add').click(resetForm);
        $('#menu-reset').click(function () {
            if ($('#id').val() == '') {
                resetForm();
            } else {
                detail(null, null, $('#id').val());
            }
        });
        $('#menu-remove-batch').click(removeBatch);
        $('#menu-remove').click(remove);
        resetForm();
    });

    function initTree() {
        $.getJSON('list', function (rs) {
            var root = [], map = {};
            $(rs.data.list).each(function (index, _this) {
                _this.text = _this.name;
                _this.state = {
                    opened: true
                }
                var parent = map[_this.pid];
                if (!parent) {
                    root.push(_this);
                } else {
                    if (!parent.children) {
                        parent.children = [];
                    }
                    parent.children.push(_this);
                }
                map[_this.id] = _this;
            });
            initPidOption(root);
            $('#menu-tree').jstree('destroy').on('activate_node.jstree', detail).jstree({
                'core': {
                    'data': root
                },
                "plugins": ["checkbox"],
                "checkbox": {
                    "keep_selected_style": false
                }
            });
        });
    }

    function resetForm() {
        $('#menu-remove').prop('disabled', true);
        var $form = $('#form-menu');
        $form[0].reset();
        $form.find('[name]').val('');
        $form.find('select').trigger('change');
        initPidOption();
        $form.data('bootstrapValidator').resetForm();
        return false;
    }

    function detail(tree, event, id) {
        id = id || event.node.id;
        resetForm();
        $.getJSON('detail?id=' + id, function (rs) {
            var entity = rs.data.entity || {};
            $('#form-menu').fillJson(entity);
            $('#menu-remove').prop('disabled', false);
            initPidOption();
            $('#form-menu').find('select').trigger('change');
        });

    }

    function removeBatch() {
        var nodes = $('#menu-tree').jstree('get_checked');
        if (nodes.length == 0) {
            base.top().toastr.error('请选择要删除的菜单');
            return;
        }
        bootbox.confirm('确定要删除所选菜单吗？', function (res) {
            if (!res) {
                return;
            }
            var ids = [];
            $(nodes).each(function () {
                ids.push({name: 'id', value: this});
            });
            _remove(ids)
        });
    }

    function remove() {
        bootbox.confirm('确定要删除当前菜单吗？', function (res) {
            if (!res) {
                return;
            }
            _remove([{name: 'id', value: $('#id').val()}])
        });
    }

    function _remove(ids) {
        $.post('remove', ids, function (rs) {
            base.ajaxBack(rs, function () {
                initTree();
                resetForm();
            });
        });
    }

    function initPidOption(list) {
        var $pid = $('#pid'), id = $('#id').val(), path = $('#path').val() + ',' + id + ',';
        list && $pid.html('<option value="0">顶级菜单</option>'),
        list && appendOption($pid, list, '　');
        $pid.children().each(function () {
            var menu = $(this).data('menu'),
                disabled = id && menu && (menu.id == id || menu.pid == id || menu.path.indexOf(path) > -1);
            $(this).prop('disabled', disabled);
        });
        $('#pid').select2();
    }

    function appendOption($pid, list, prefix) {
        $(list).each(function () {
            $pid.append($('<option />').val(this.id).text(prefix + this.name).data('menu', this));
            appendOption($pid, this.children, prefix + '　');
        });
    }
})(this, jQuery);